package com.hdjk.view.fragment.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.activity.main.LoginActivity;
import com.hdjk.view.activity.personalcenter.AccountSetActivity;
import com.hdjk.view.activity.personalcenter.BuyPlanListActivity;
import com.hdjk.view.activity.personalcenter.FavoriteActivity;
import com.hdjk.view.activity.personalcenter.HistoricalTransactionActivity;
import com.hdjk.view.activity.personalcenter.MyIntegralActivity;
import com.hdjk.view.activity.personalcenter.RecommendActivity;
import com.hdjk.view.activity.personalcenter.RedeemDetailActivity;
import com.hdjk.view.activity.personalcenter.WalletActivity;
import com.hdjk.view.adapter.HoldingFundListAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.config.Constant;
import com.hdjk.view.entity.HoldingFundEntity;
import com.hdjk.view.entity.TotalAssetsEntity;
import com.hdjk.view.entity.WalletHoldingEntity;
import com.hdjk.view.network.PersonalNetWork;
import com.hdjk.view.network.WalletNetWork;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseFram;
import com.lst.projectlib.component.ListView.ListViewForScrollView;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 个人中心Fragment
 * Created by sxy on 2017/11/1.
 */

public class PersonalCenterFragment extends BaseFram implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener{
    private List<HoldingFundEntity> funds;
    private HoldingFundListAdapter mAdapter;
    private boolean isRefresh=false;

    // Content View Elements
    private SwipeRefreshLayout mSwipeLayout;
    private ScrollView sv_main;
    private LinearLayout lin_not_login;
    private Button btn_register;
    private Button btn_login;
    private LinearLayout lin_login;
    private TextView tv_assets;
    private TextView tv_yesterday;
    private TextView tv_sum;
    private LinearLayout lin_collection;
    private LinearLayout lin_history;
    private LinearLayout lin_recommend;
    private LinearLayout lin_set;
    private LinearLayout lin_plan;
    private LinearLayout lin_wallet;
    private TextView tv_wallet_value;
    private TextView tv_wallet_profit;
    private TextView tv_integral;
    private ListViewForScrollView lv_data_list;
    // End Of Content View Elements

    private void bindViews(View view) {
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_ly);
        sv_main= (ScrollView) view.findViewById(R.id.sv_main);
        lin_not_login = (LinearLayout) view.findViewById(R.id.lin_not_login);
        btn_register = (Button) view.findViewById(R.id.btn_register);
        btn_login = (Button) view.findViewById(R.id.btn_login);
        lin_login = (LinearLayout) view.findViewById(R.id.lin_login);
        tv_assets = (TextView) view.findViewById(R.id.tv_assets);
        tv_yesterday = (TextView) view.findViewById(R.id.tv_yesterday);
        tv_sum = (TextView) view.findViewById(R.id.tv_sum);
        lin_collection = (LinearLayout) view.findViewById(R.id.lin_collection);
        lin_history = (LinearLayout) view.findViewById(R.id.lin_history);
        lin_recommend = (LinearLayout) view.findViewById(R.id.lin_recommend);
        lin_set = (LinearLayout) view.findViewById(R.id.lin_set);
        lin_plan = (LinearLayout) view.findViewById(R.id.lin_plan);
        lin_wallet = (LinearLayout) view.findViewById(R.id.lin_wallet);
        tv_wallet_value = (TextView) view.findViewById(R.id.tv_wallet_value);
        tv_wallet_profit = (TextView) view.findViewById(R.id.tv_wallet_profit);
        tv_integral = (TextView) view.findViewById(R.id.tv_integral);
        lv_data_list = (ListViewForScrollView) view.findViewById(R.id.lv_data_list);
    }


    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal_center, container, false);
        bindViews(view);
        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        lin_collection.setOnClickListener(this);
        lin_history.setOnClickListener(this);
        lin_recommend.setOnClickListener(this);
        lin_set.setOnClickListener(this);
        lin_plan.setOnClickListener(this);
        lin_wallet.setOnClickListener(this);
        tv_integral.setOnClickListener(this);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.bg_common_red, R.color.bg_common_red,
                R.color.bg_common_red, R.color.bg_common_red);
        // 设置手指在屏幕下拉多少距离会触发下拉刷新
        mSwipeLayout.setDistanceToTriggerSync(200);
        sv_main.getViewTreeObserver().addOnScrollChangedListener(new  ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                mSwipeLayout.setEnabled(sv_main.getScrollY()==0);
            }
        });
        IntentFilter filter = new IntentFilter(Constant.INTENT_FILTER_STRING_AFTER_BUY_SUCCESS);
        filter.addAction(Constant.INTENT_FILTER_STRING_AFTER_REDEEM_SUCCESS);
        filter.addAction(Constant.INTENT_FILTER_STRING_AFTER_WALLET_EDIT);
        getContext().registerReceiver(mReceiver,filter);
        lin_login.setFocusable(true);
        lin_login.setFocusableInTouchMode(true);
        lin_login.requestFocus();
        return view;
    }

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(UserTokenUtil.getToken(getContext()))) {
            lin_login.setVisibility(View.VISIBLE);
            lin_not_login.setVisibility(View.GONE);
        } else {
            lin_login.setVisibility(View.GONE);
            lin_not_login.setVisibility(View.VISIBLE);
        }
        funds=new ArrayList<>();
        mAdapter=new HoldingFundListAdapter(getContext());
        mAdapter.setDataList(funds);
        lv_data_list.setAdapter(mAdapter);
        lv_data_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int index = (int) id;
                Intent intent = new Intent(mContext, RedeemDetailActivity.class);
                intent.putExtra("title", funds.get(index).getFundName());
                if (funds.get(index).isGroup()) {
                    intent.putExtra("type", "2");
                    intent.putExtra("portfolioId", funds.get(index).getPortfolioId());
                } else {
                    if (funds.get(index).getFundType().equals("fund"))
                        intent.putExtra("type", "0");
//                    else if (funds.get(index).getFundType().equals("collective"))
//                        intent.putExtra("type", "1");
                    else
                        intent.putExtra("type", "1");

                    intent.putExtra("portfolioId", funds.get(index).getPortfolioId());
                    intent.putExtra("fundCode", funds.get(index).getFundCode());
                }

                startActivity(intent);
            }
        });
        lv_data_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                boolean enable = false;
                if(lv_data_list != null && lv_data_list.getChildCount() > 0){
                    // check if the first item of the list is visible
                    boolean firstItemVisible = lv_data_list.getFirstVisiblePosition() == 0;
                    // check if the top of the first item is visible
                    boolean topOfFirstItemVisible = lv_data_list.getChildAt(0).getTop() == 0;
                    // enabling or disabling the refresh layout
                    enable = firstItemVisible && topOfFirstItemVisible;
                }
                mSwipeLayout.setEnabled(enable);
            }
        });
        if (UserTokenUtil.isLogin(getContext())&&UserTokenUtil.isOpenAccount(getContext())){
            onRefresh();
        }
    }

    private void getHoldingFunds() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(getContext()));
            PersonalNetWork.getHoldingFund(UserTokenUtil.getToken(getContext()),obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    if (mSwipeLayout.isRefreshing()){
                        mSwipeLayout.setRefreshing(false);
                    }
                    isRefresh=false;
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof List) {
                        if (UserTokenUtil.isLogin(getContext())) {
                            funds = (List<HoldingFundEntity>) msg.getData();
                            if (mAdapter == null) {
                                mAdapter = new HoldingFundListAdapter(getContext());
                                mAdapter.setDataList(funds);
                                lv_data_list.setAdapter(mAdapter);
                            } else {
                                mAdapter.setDataList(funds);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getTotelAssets() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(getContext()));
            PersonalNetWork.getTotalAssets(UserTokenUtil.getToken(getContext()),obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    if (mSwipeLayout.isRefreshing()){
                        mSwipeLayout.setRefreshing(false);
                    }
                    isRefresh=false;
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof TotalAssetsEntity) {
                        TotalAssetsEntity entity = (TotalAssetsEntity) msg.getData();
                        if (!TextUtils.isEmpty(entity.getCurrentAmount()) && !"null".equals(entity.getCurrentAmount()))
                            tv_assets.setText(entity.getCurrentAmount());
                        if (!TextUtils.isEmpty(entity.getProfitLossDaily()) && !"null".equals(entity.getProfitLossDaily()))
                            tv_yesterday.setText(entity.getProfitLossDaily());
                        if (!TextUtils.isEmpty(entity.getAccumulatedProfitLoss()) && !"null".equals(entity.getAccumulatedProfitLoss()))
                            tv_sum.setText(entity.getAccumulatedProfitLoss());
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getWalletHoldings(){
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(getContext()));
            WalletNetWork.getWalletHoldings(UserTokenUtil.getToken(getContext()),obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    if (mSwipeLayout.isRefreshing()){
                        mSwipeLayout.setRefreshing(false);
                    }
                    isRefresh=false;
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof WalletHoldingEntity) {
                        WalletHoldingEntity entity = (WalletHoldingEntity) msg.getData();
                        if (!TextUtils.isEmpty(entity.getPreProfitLoss()) && !"null".equals(entity.getPreProfitLoss()))
                            tv_wallet_profit.setText(entity.getPreProfitLoss());
                        if (!TextUtils.isEmpty(entity.getTotalCurrentValue()) && !"null".equals(entity.getTotalCurrentValue()))
                            tv_wallet_value.setText(entity.getTotalCurrentValue());
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserTokenUtil.isLogin(getContext())) {
            lin_login.setVisibility(View.VISIBLE);
            lin_not_login.setVisibility(View.GONE);
            if (!UserTokenUtil.isOpenAccount(getContext())) {
                tv_assets.setText("0.00");
                tv_yesterday.setText("0.00");
                tv_sum.setText("0.00");
                tv_wallet_value.setText("0.00");
                tv_wallet_profit.setText("0.00");
                funds.clear();
                mAdapter.notifyDataSetChanged();
                mSwipeLayout.setEnabled(false);
            }else {
                if (isRefresh){
                    onRefresh();
                }
                mSwipeLayout.setEnabled(true);
            }
        } else {
            lin_login.setVisibility(View.GONE);
            lin_not_login.setVisibility(View.VISIBLE);
            tv_wallet_value.setText("0.00");
            tv_wallet_profit.setText("0.00");
            funds.clear();
            mAdapter.notifyDataSetChanged();
            mSwipeLayout.setEnabled(false);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_login:
//                intent = new Intent(getContext(), LoginActivity.class);
//                startActivityForResult(intent,123);
                break;
            case R.id.tv_integral:
                if (UserTokenUtil.isLogin(getContext())) {
                    intent = new Intent(getContext(), MyIntegralActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivityForResult(intent,123);
                }
                break;
            case R.id.btn_register:
                intent = new Intent(getContext(), LoginActivity.class);
                startActivityForResult(intent,123);
                break;
            case R.id.lin_collection:
                if (UserTokenUtil.isLogin(getContext())) {
                    intent = new Intent(getContext(), FavoriteActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivityForResult(intent,123);
                }
                break;
            case R.id.lin_history:
                if (UserTokenUtil.isLogin(getContext())) {
                    if (!UserTokenUtil.isOpenAccount(getContext())) {
                        ToastUtils.showShortToast(getContext(), "您未开户，请先开户");
                        return;
                    }
                    intent = new Intent(getContext(), HistoricalTransactionActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivityForResult(intent,123);
                }
                break;
            case R.id.lin_recommend:
                if (UserTokenUtil.isLogin(getContext())) {
                    intent = new Intent(getContext(), RecommendActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivityForResult(intent,123);
                }
                break;
            case R.id.lin_set:
                if (UserTokenUtil.isLogin(getContext())) {
                    intent = new Intent(getContext(), AccountSetActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivityForResult(intent,123);
                }
                break;
            case R.id.lin_plan:
                if (UserTokenUtil.isLogin(getContext())) {
                    if (!UserTokenUtil.isOpenAccount(getContext())) {
                        ToastUtils.showShortToast(getContext(), "您未开户，请先开户");
                        return;
                    }
                    intent = new Intent(getContext(), BuyPlanListActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivityForResult(intent,123);
                }
                break;
            case R.id.lin_wallet:
                if (UserTokenUtil.isLogin(getContext())) {
                    if (!UserTokenUtil.isOpenAccount(getContext())) {
                        ToastUtils.showShortToast(getContext(), "您未开户，请先开户");
                        return;
                    }
                    intent = new Intent(getContext(), WalletActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivityForResult(intent,123);
                }
                break;
        }
    }

    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constant.INTENT_FILTER_STRING_AFTER_BUY_SUCCESS)
                    || intent.getAction().equals(Constant.INTENT_FILTER_STRING_AFTER_REDEEM_SUCCESS)||intent.getAction().equals(Constant.INTENT_FILTER_STRING_AFTER_WALLET_EDIT)){
                isRefresh=true;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContext().unregisterReceiver(mReceiver);
    }

    @Override
    public void onRefresh() {
        getTotelAssets();
        getHoldingFunds();
        getWalletHoldings();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==123&&resultCode==111){
            tv_assets.setText("0.00");
            tv_yesterday.setText("0.00");
            tv_sum.setText("0.00");
            tv_wallet_value.setText("0.00");
            tv_wallet_profit.setText("0.00");
            onRefresh();
        }
    }
}
